package com.pdstudio.weather;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.pdstudio.app.Application;
import com.pdstudio.bean.WeatherProfile;
import com.pdstudio.http.WeatherHttpMethod;
import com.pdstudio.view.SwipeBackActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/*
 * 
 * 选择添加城市*/
public class AddCitysActivity extends SwipeBackActivity {

	public LayoutInflater inflater;
	private View customLiveIndexTitleView;
	private TextView txtTitle;

	final String FOCUSCITYS = "focuscitys";// 存储的key
	List<String> saveCitys;
	Map<String, WeatherProfile> weathers;// 城市code对应的实时天气

	SharedPreferences preferences; // 存储用户关注的城市
	SharedPreferences.Editor editor;

	GridView gridview;
	private String currentCityCode = "";

	private Handler handler;
	private Application mApplication;
	
	private ImageView ivBack;

	private synchronized void ChangeCurrentCity(String value) {
		this.currentCityCode = value;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_citys_main);

		ivBack = (ImageView) findViewById(R.id.title2_back);
		ivBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				AddCitysActivity.this.finish();

			}

		});
		
		mApplication = Application.getInstance();

		handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					try {
						ProgressBar pb = (ProgressBar) findViewById(R.id.pb_add_city);
						pb.setVisibility(View.GONE);
					} catch (Exception e) {
						e.printStackTrace();
					}
					gridview.setAdapter(new AddCityAdapter());
				}
			}
		};

		inflater = (LayoutInflater) this
				.getSystemService(LAYOUT_INFLATER_SERVICE);

		if (true) {// TODO 这里判断天气情况
			LinearLayout layout = (LinearLayout) findViewById(R.id.addcityslayout);
			layout.setBackground(getResources().getDrawable(R.drawable.bgsun));
		}

		customLiveIndexTitleView = findViewById(R.id.title_photogallery);
		txtTitle = (TextView) customLiveIndexTitleView
				.findViewById(R.id.title2_text_nav);
		txtTitle.setText("城市添加");

		gridview = (GridView) findViewById(R.id.photogridview1);

		InitialView();
	}

	/*
	 * 获取天气的图标
	 */
	public int GetWeatherIcon(String climate) {
		int result = 0;
		try {
			result = mApplication.getWidgetWeatherIcon(climate);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	private void InitialView() {
		saveCitys = new ArrayList<String>();
		weathers = new HashMap<String, WeatherProfile>();

		// 获取只能被本应用程序读、写的SharedPreferences对象
		preferences = getSharedPreferences(FOCUSCITYS, MODE_WORLD_READABLE);
		// 获得修改器
		editor = preferences.edit();
		try {
			String temp = preferences.getString(FOCUSCITYS, "");// 存储的城市用;分开
			if (temp != null && !temp.equals("")) {
				String[] temps = temp.split(";");
				if (temps != null && temps.length > 0) {
					for (int i = 0; i < temps.length; i++) {
						if (!saveCitys.contains(temps[i])) {
							saveCitys.add(temps[i]);
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			saveCitys.add("xo");// 用来标记是添加按钮
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 初始化天气信息
		try {
			Thread thread = new Thread() {
				@Override
				public void run() {
					WeatherHttpMethod hwm = new WeatherHttpMethod(
							getApplicationContext());
					if (saveCitys != null) {
						for (int i = 0; i < saveCitys.size(); i++) {
							WeatherProfile w = hwm.Getweatherforecasts(mApplication.getSharePreferenceUtil().getAuthCode(),
									saveCitys.get(i));
							if (saveCitys.get(i) != "xo" && w != null
									&& !weathers.containsKey(saveCitys.get(i))) {
								weathers.put(saveCitys.get(i), w);
							}
						}
						Message m = new Message();
						m.what = 0;
						handler.sendMessage(m);
					}
				}
			};
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 复写onActivityResult，这个方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 可以根据多个请求代码来作相应的操作 10表示添加城市成功
		if (10 == resultCode) {
			InitialView();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public class AddCityAdapter extends BaseAdapter {

		private Context context;

		public void AddCityAdapter(Context context) {
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return saveCitys.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return saveCitys.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View v = inflater.inflate(R.layout.activity_add_citys_main_item,
					null);
			try {
				String flag = saveCitys.get(position);// flag为x0时更换为添加按钮并注册单独的事件
				if (flag.equals("xo")) {
					LinearLayout tv1 = (LinearLayout) v
							.findViewById(R.id.add_city_linearlayout);
					tv1.setVisibility(View.INVISIBLE);
					ImageView add = (ImageView) v
							.findViewById(R.id.add_city_iv);
					add.setImageResource(R.drawable.addcity);
					add.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							// Toast.makeText(getApplicationContext(),
							// "this is add button", 0).show();
							Intent intent = new Intent(AddCitysActivity.this,
									SearchCitysActivity.class);
							startActivityForResult(intent, 1);
						}

					});
				} else {
					TextView tv1 = (TextView) v
							.findViewById(R.id.phototextview1);
					tv1.setText(saveCitys.get(position));
					TextView tv2 = (TextView) v
							.findViewById(R.id.phototextview2);
					tv2.setText(weathers.get(saveCitys.get(position)) == null ? ""
							: weathers.get(saveCitys.get(position)).weatherStatus);
					ImageView add = (ImageView) v
							.findViewById(R.id.add_city_iv);
					add.setImageResource(R.drawable.addcityback);

					ImageView wic = (ImageView) v
							.findViewById(R.id.add_city_iv_w);
					wic.setImageResource(GetWeatherIcon(weathers.get(saveCitys
							.get(position)) == null ? "" : weathers
							.get(saveCitys.get(position)).weatherStatus));

					TextView tvh = (TextView) v
							.findViewById(R.id.add_city_high_tem);
					tvh.setText(weathers.get(saveCitys.get(position)) == null ? ""
							: weathers.get(saveCitys.get(position)).highTemp);
					TextView tvl = (TextView) v
							.findViewById(R.id.add_city_low_tem);
					tvl.setText(weathers.get(saveCitys.get(position)) == null ? ""
							: weathers.get(saveCitys.get(position)).lowTemp);
					ChangeCurrentCity(saveCitys.get(position));// 改变选中项的值
					
					add.setOnClickListener(new OnClickListener(){

						@Override
						public void onClick(View v) {
							// TODO Auto-generated method stub
							Intent intent=new Intent(AddCitysActivity.this,ForecastActivity.class);
							startActivity(intent);
							finish();
						}});
					
					add.setOnLongClickListener(new OnLongClickListener() {

						@Override
						public boolean onLongClick(View v) {
							// TODO Auto-generated method stub

							AlertDialog ad = new AlertDialog.Builder(
									AddCitysActivity.this)
									.setTitle("取消关注")
									.setIcon(android.R.drawable.ic_dialog_info)
									.setMessage("是否取消关注该城市？")
									.setPositiveButton(
											"确定",
											new DialogInterface.OnClickListener() {
												public void onClick(
														DialogInterface dialog,
														int whichButton) {
													// 这里添加点击确定后的逻辑
													// 删除
													try {
														String precitys = preferences
																.getString(
																		FOCUSCITYS,
																		"");// 存储的城市用;分开
														String newpres = "";
														if (precitys != null
																&& !precitys
																		.equals("")) {
															String[] temps = precitys
																	.split(";");
															for (int i = 0; i < temps.length; i++) {
																if (temps[i] != null
																		&& !temps[i]
																				.equals(currentCityCode)) {
																	newpres = newpres
																			+ temps[i]
																			+ ";";
																}
																editor.putString(
																		FOCUSCITYS,
																		newpres);
																editor.commit();
															}
														}
														Toast.makeText(
																AddCitysActivity.this,
																"已取消该城市关注！",
																Toast.LENGTH_SHORT)
																.show();
														InitialView();
													} catch (Exception e) {
														e.printStackTrace();
														Toast.makeText(
																AddCitysActivity.this,
																"取消关注失败！",
																Toast.LENGTH_SHORT)
																.show();
													}
												}
											}).setNegativeButton("返回", null)
									.show();

							return false;
						}
					});
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return v;
		}

	}

	// 长按菜单响应函数
	@Override
	public boolean onContextItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case 0:
			// 删除
			try {
				String precitys = preferences.getString(FOCUSCITYS, "");// 存储的城市用;分开
				String newpres = "";
				if (precitys != null && !precitys.equals("")) {
					String[] temps = precitys.split(";");
					for (int i = 0; i < temps.length; i++) {
						if (temps[i] != null
								&& !temps[i].equals(currentCityCode)) {
							newpres = newpres + temps[i] + ";";
						}
					}
				}
				Toast.makeText(AddCitysActivity.this, "已取消该城市关注！",
						Toast.LENGTH_SHORT).show();
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(AddCitysActivity.this, "取消关注失败！",
						Toast.LENGTH_SHORT).show();
			}

			break;
		default:
			break;
		}
		return super.onContextItemSelected(item);

	}
}
